package ytmc.setup.security;

import java.math.BigInteger;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author Kicok
 */
public class AESPasswordCipher implements PasswordCipher
{
    private final byte[] key = new BigInteger( "641EA1F4505EA587CC19535F50644AD4", 16 ).toByteArray();

    private SecretKeySpec keySpec;
    private Cipher cipher;
    private Base64 base64Codec;


    public AESPasswordCipher()
    {
        try
        {
            keySpec = new SecretKeySpec( key, "AES" );
            cipher = Cipher.getInstance( "AES" );
            base64Codec = new Base64();
        }
        catch( GeneralSecurityException e )
        {
            System.out.print( e );
        }
    }


    /**
     *
     * @param password Plain password
     * @return Base64-encoded AES-encrypted password
     */
    @Override
    public String encrypt( String password )
    {
        if( StringUtils.isEmpty( password ) )
        {
            return "";
        }

        try
        {
            cipher.init( Cipher.ENCRYPT_MODE, keySpec );
            byte[] encPasswordBytes = cipher.doFinal( password.getBytes() );

            return base64Codec.encodeToString( encPasswordBytes );
        }
        catch( GeneralSecurityException e )
        {
            System.out.print( e );
            return "";
        }
    }

    /**
     *
     * @param encryptedPassword Base64-encoded AES-encrypted password
     * @return Plain password
     */
    @Override
    public String decrypt( String encryptedPassword )
    {
        if( StringUtils.isEmpty( encryptedPassword ) )
        {
            return "";
        }

        try
        {
            cipher.init( Cipher.DECRYPT_MODE, keySpec );
            byte[] decPasswordBytes = cipher.doFinal( base64Codec.decode( encryptedPassword ) );

            return new String( decPasswordBytes );
        }
        catch( GeneralSecurityException e )
        {
            System.out.print( e );
            return "";
        }
    }
}
